package fun.shuofeng.juc.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicStampedReferenceDemo01 {
    public static void main(String[] args) throws InterruptedException {
        AtomicStampedReference<String> asr = new AtomicStampedReference<String>("A", 0);
        int stamp = asr.getStamp();
        String prev = asr.getReference();
        System.out.println("current stamp: " + stamp);
        otherThread(asr);
        TimeUnit.SECONDS.sleep(1);
        System.out.println("current stamp: " + stamp);
        boolean result = asr.compareAndSet(prev, "A", stamp, stamp + 1);
        System.out.println("main :" + result);
        // current stamp: 0
        // t1 stamp:0
        // t2 stamp:1
        // current stamp: 0
        // main :false
    }

    private static void otherThread(AtomicStampedReference<String> asr) {
        new Thread(() -> {
            int stamp = asr.getStamp();
            String prev = asr.getReference();
            System.out.println("t1 stamp:" + stamp);
            asr.compareAndSet(prev, "B", stamp, stamp + 1);
        }).start();
        new Thread(() -> {
            int stamp = asr.getStamp();
            String prev = asr.getReference();
            System.out.println("t2 stamp:" + stamp);
            asr.compareAndSet(prev, "A", stamp, stamp + 1);
        }).start();
    }
}
